//
//  YLMineViewController.m
//  YLFinanceService
//
//  Created by she1323 on 2017/8/31.
//  Copyright © 2017年 she1323. All rights reserved.
//

#import "YLMineViewController.h"
#import <Masonry.h>
#import "YLMineHeader.h"
#import "YLGlobeHeader.h"
#import "YLHeaderBaseView.h"
#import "YLMineViewModel.h"
#import "YLTitleArrowNoSubCell.h"
#import "YLTitleAllowCell.h"
#import "YLIconTitleSpotTableViewCell.h"
#import "YLIconTitleNumberCell.h"
#import "YLIconTitleModel.h"
#import "YLPersonaInformationController.h"
#import "YLAccountSettingController.h"
#import "YLDisplayAmountDescriptionView.h"
#import "YLAmountInvestedViewController.h"
#import "YLExpectedReturnViewController.h"
#import "YLRevenueOnArrivalViewController.h"
#import "YLMonthlyBillController.h"
#import <MJRefresh.h>
#import "WHProgressHUD.h"
#import "YLAdView.h"
#import "YLAdViewModel.h"
#import "YLAdModel.h"
#import "WHWebViewController.h"
@interface YLMineViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) YLMineViewModel *viewModel;
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, weak) YLMineHeader *header;
@property (nonatomic, strong) YLAdViewModel *adViewModel;
@end

@implementation YLMineViewController

- (YLAdViewModel *)adViewModel
{
    if (!_adViewModel) {
        _adViewModel = [[YLAdViewModel alloc] init];
        _adViewModel.conditionId = 14;
    }
    return _adViewModel;
}


- (YLMineViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[YLMineViewModel alloc] init];
    }
    return _viewModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setUpTableView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"YLLoadMyInfoNoti" object:nil];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    __weak typeof(self) weakSelf = self;
    [[self.adViewModel.requestCommand execute:nil] subscribeNext:^(id  _Nullable x) {
        YLAdModel *model = x;
        YLAdView *adView = [[YLAdView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        adView.iconUrl = model.noticeIcon;
        [[UIApplication sharedApplication].keyWindow addSubview:adView];
        
        adView.clickBlock = ^{
            if (model.followActionTypeInt == 2) {
                WHWebViewController *webCon = [[WHWebViewController alloc] init];
                webCon.url = model.followAction;
                [weakSelf.navigationController pushViewController:webCon animated:YES];
            }
        };
    }];
}

- (void)loadData
{
    __weak typeof(self) weakSelf = self;
    [[self.viewModel.requestCommand execute:nil] subscribeNext:^(id  _Nullable x) {
        weakSelf.header.model = self.viewModel.myInfoModel;
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}


- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

// 仅设置当前页面
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [WHProgressHUD dismiss];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navBackground"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)setUpTableView
{
    __weak typeof(self) weakSelf = self;
    YLMineHeader *header = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([YLMineHeader class]) owner:nil options:nil].lastObject;
    CGFloat baseH = 225 + 100;
    _header = header;
    baseH = ([UIApplication sharedApplication].statusBarFrame.size.height - 20) + baseH;

    YLHeaderBaseView *baseView = [[YLHeaderBaseView alloc] initWithFrame:CGRectMake(0, 0, YLScreenW, baseH)];
    header.frame = baseView.frame;
    [baseView addSubview:header];
    
    [header mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.left.bottom.mas_equalTo(baseView);
    }];
    
    // 点击头像
    [[header.iconTap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        
        if (!weakSelf.viewModel.myInfoModel) {
            return ;
        }
        
        YLPersonaInformationController *con = [[YLPersonaInformationController alloc] init];
        con.model = weakSelf.viewModel.myInfoModel;
        
        [weakSelf.navigationController pushViewController:con animated:YES];
    }];
    
    // 点击说明
    [header.showExplainSignal subscribeNext:^(id  _Nullable x) {
        YLDisplayAmountDescriptionView *dis = [[YLDisplayAmountDescriptionView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        dis.type = YLDisplayAmountDescriptionViewTypeAmount;
        [weakSelf.tabBarController.view addSubview:dis];
    }];
    
    // 在投金额
    [header.amountInvestedSubject subscribeNext:^(id  _Nullable x) {
        YLAmountInvestedViewController *amount = [[YLAmountInvestedViewController alloc] init];
        [weakSelf.navigationController pushViewController:amount animated:YES];
    }];
    
    // 到账收益
    [header.revenueOnArrivalSubject subscribeNext:^(id  _Nullable x) {
        YLRevenueOnArrivalViewController *revenue = [[YLRevenueOnArrivalViewController alloc] init];
        [weakSelf.navigationController pushViewController:revenue animated:YES];
    }];
    
    // 预期收益
    [header.expectedReturnSubject subscribeNext:^(id  _Nullable x) {
        YLExpectedReturnViewController *expected = [[YLExpectedReturnViewController alloc] init];
        [weakSelf.navigationController pushViewController:expected animated:YES];
    }];
    
    // 月账单
    [header.monthlyBillSubject subscribeNext:^(id  _Nullable x) {
        YLMonthlyBillController *bill = [[YLMonthlyBillController alloc] init];
        [weakSelf.navigationController pushViewController:bill animated:YES];
    }];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView = tableView;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLTitleArrowNoSubCell class]) bundle:nil] forCellReuseIdentifier:[YLTitleArrowNoSubCell cellID]];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLTitleAllowCell class]) bundle:nil] forCellReuseIdentifier:[YLTitleAllowCell cellID]];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLIconTitleSpotTableViewCell class]) bundle:nil] forCellReuseIdentifier:[YLIconTitleSpotTableViewCell cellID]];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLIconTitleNumberCell class]) bundle:nil] forCellReuseIdentifier:[YLIconTitleNumberCell cellID]];
    
    [self.view addSubview:tableView];
    tableView.tableHeaderView = baseView;
    tableView.backgroundColor = YLBackGroundColor;
    tableView.delegate = self;
    tableView.dataSource = self;
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.left.bottom.mas_equalTo(weakSelf.view);
    }];
    
//    [[self.viewModel.requestCommand execute:nil] subscribeNext:^(id  _Nullable x) {
//        header.model = weakSelf.viewModel.myInfoModel;
//        [tableView reloadData];
//    }];
    
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadData];
    }];
    
    [tableView.mj_header beginRefreshing];
    
    [self.viewModel.wh_loadDataErrorSubject subscribeNext:^(id  _Nullable x) {
        [tableView.mj_header endRefreshing];
    }];
    
    if (@available(iOS 11.0, *)) {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
    }
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.viewModel.groups.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    YLIconTitleModelGroup *group = self.viewModel.groups[section];
    return group.models.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YLIconTitleModelGroup *group = self.viewModel.groups[indexPath.section];
    YLIconTitleModel *model = group.models[indexPath.row];
    
    // 有副标题
    if ([model isKindOfClass:[YLIconTitleContentModel class]]) {
        YLTitleAllowCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLTitleAllowCell cellID]];
        cell.contentModel = (YLIconTitleContentModel *)model;
        return cell;
    }
    
    // 有点
    if ([model isKindOfClass:[YLIconTitleSpotModel class]]) {
        YLIconTitleSpotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLIconTitleSpotTableViewCell cellID]];
        cell.spotModel = (YLIconTitleSpotModel *)model;
        return cell;
    }
    
    // 有提示数字
    if ([model isKindOfClass:[YLIconTitleNumberModel class]]) {
        YLIconTitleNumberCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLIconTitleNumberCell cellID]];
        cell.numberModel = (YLIconTitleNumberModel *)model;
        return cell;
    }
    
    // 最简单的
    YLTitleArrowNoSubCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLTitleArrowNoSubCell cellID]];
    
    if (indexPath.row == group.models.count - 1) {
        cell.hiddenLine = YES;
    } else {
        cell.hiddenLine = NO;
    }
    
    cell.iconTitleModel = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return YLScreenW * 24 / 750.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [YLTitleArrowNoSubCell cellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    

    YLIconTitleModelGroup *group = self.viewModel.groups[indexPath.section];
    YLIconTitleModel *model = group.models[indexPath.row];
    if (model.clickBlock) {
        NSString *name = model.clickBlock();
        if (name) {
        [self.navigationController pushViewController:[[NSClassFromString(name) alloc] init] animated:YES];
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [UIView new];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



@end
